package servlets;

import java.io.IOException;
import javaPersistence.DBConexConSoft;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;

/**
 * Servlet implementation class LoadReports
 */
@WebServlet("/LoadReports")
public class LoadReports extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoadReports() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			JasperPrint jasperPrint = new JasperPrint();
			DBConexConSoft dbCon = DBConexConSoft.getInstance();
			ServletOutputStream servletOutputStream = response.getOutputStream();
			
			String url = "";
			response.setContentType("application/pdf");
			System.out.println("Aux: "+request.getParameter("aux"));
			if(request.getParameter("aux").equals("clientes")){
				url = "C:\\reportClient.jasper";
				JasperReport cliente = (JasperReport) JRLoader.loadObject(url);
				jasperPrint = JasperFillManager.fillReport(cliente,null, dbCon.getConexion());
			}
			if(request.getParameter("aux").equals("usuario")){
				url = "C:\\reportUser.jasper";
				JasperReport usuario = (JasperReport) JRLoader.loadObject(url);
				jasperPrint = JasperFillManager.fillReport(usuario,null, dbCon.getConexion());
			}
			if(request.getParameter("aux").equals("ventas")){
				url = "C:\\reportSales.jasper";
				JasperReport ventas = (JasperReport) JRLoader.loadObject(url);
				jasperPrint = JasperFillManager.fillReport(ventas,null, dbCon.getConexion());
			}
			
			System.out.println("url: "+url);
			
			JasperExportManager.exportReportToPdfStream(jasperPrint,servletOutputStream);
			servletOutputStream.flush();
			servletOutputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
